<template>
  <div class="class=moon-tabs">
    <div class="moon-tabs-nav" ref="container">
      <div
        class="moon-tabs-nav-item"
        :class="{disabledTitle: disabledTitles.includes(t)}"
        v-for="(t,index) in titles"
        :key="index"
        ref="items"
        @click="select(t)"
      >{{t}}</div>
      <div class="moon-tabs-nav-indicator" ref="indicator"></div>
    </div>
    <div class="moon-tabs-content">
      <slot />
    </div>
  </div>
</template>

<script>
export default {
  props: {
    selected: {
      type: String
    },
    disabled: {
      type: Boolean,
      defaults: false
    }
  },
  data() {
    const defaults = this.$slots.default
    defaults.forEach((tag) => {
      if (tag.componentOptions.tag !== 'moon-tab') {
        throw new Error('moon-tabs 字标签必须是 moon-tab')
      }
    })
    const titles = defaults.map((tag) => {
      return tag.data.attrs.title
    })
    const disabledTitles = titles.filter((item, index) => {
      return defaults[index].data.attrs.disabled
    })
    console.log(disabledTitles)
    return {
      defaults,
      titles,
      disabledTitles
    }
  },
  computed: {
    current() {
      return this.defaults.find((tag) => tag.data.attrs.title === this.selected)
    }
  },
  methods: {
    setIndicator() {
      const indicator = this.$refs.indicator
      const container = this.$refs.container
      const items = this.$refs.items
      const selectedItem = items.find((div) => div.innerText === this.selected)

      const { width } = selectedItem.getBoundingClientRect()
      indicator.style.width = width + 'px'
      const { left: left1 } = container.getBoundingClientRect()
      const { left: left2 } = selectedItem.getBoundingClientRect()
      const left = left2 - left1
      indicator.style.left = left + 'px'
    },
    select(title) {
      if (this.disabledTitles.includes(title)) {
        return
      }
      this.$emit('update', title)
    }
  },
  mounted() {
    this.setIndicator()
  },
  updated() {
    this.setIndicator()
  }
}
</script>

<style lang="scss">
$blue: #40a9ff;
$color: #333;
$border-color: #d9d9d9;

.moon-tabs {
  &-nav {
    display: flex;
    color: $color;
    border-bottom: 1px solid $border-color;
    position: relative;

    > .disabledTitle {
      cursor: not-allowed;
      color: #ccc;
    }

    &-item {
      padding: 8px 0;
      margin: 0 16px;
      cursor: pointer;

      &:first-child {
        margin-left: 0;
      }

      &.selected {
        color: $blue;
      }
    }

    &-indicator {
      position: absolute;
      height: 3px;
      background: $blue;
      left: 0;
      bottom: -1px;
      width: 100px;
      transition: all 250ms;
    }
  }

  &-content {
    padding: 8px 0;
  }
}
</style>
